﻿using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;

namespace YQFK.Helper
{
    /// <summary>
    /// 用于微信类相关的验证
    /// </summary>
    public class WxHelper
    {
        const string appid = "wx24de838d0965879a";
        const string appSecret = "e4fdc708d6adebaf9bfe06ce83051e38";
        /// <summary>
        /// 根据code获取OpenId
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        public string OpenID(string code)
        {
            //临时登录凭证code 获取 session_key 和 openid
            string js_code = code;
            //此处填写自己小程序的appid和secret
            string serviceAddress = "https://api.weixin.qq.com/sns/jscode2session?appid="+appid+"&secret="+appSecret+"&js_code=" + js_code + "&grant_type=authorization_code";

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(serviceAddress);
            request.Method = "GET";
            request.ContentType = "textml;charset=UTF-8";
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream myResponseStream = response.GetResponseStream();
            StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.UTF8);
            string jsonData = myStreamReader.ReadToEnd();
            myStreamReader.Close();
            myResponseStream.Close();

            string jsonString = jsonData;
            JObject json = JObject.Parse(jsonString);
            if (json["openid"] == null)
            {
                return "";
            }
            else
            { 
            return json["openid"].ToString();
            }
           
        }
    }
}